﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading;
using IM.Common;
using System.Windows;
using System.Windows.Threading;
using System.Diagnostics;

namespace IM.Client
{
    class Program
    {
        /// <summary>
        /// 显示进程界面用
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="nCmdShow"></param>
        /// <returns></returns>
        [DllImport("USER32.DLL", CharSet = CharSet.Auto)]
        private static extern int ShowWindow(System.IntPtr hWnd, int nCmdShow);
        /// <summary>
        /// 显示进程界面用
        /// </summary>
        /// <param name="hWnd"></param>
        /// <returns></returns>
        [DllImport("USER32.DLL", CharSet = CharSet.Auto)]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);
        private const int SW_SHOWMAXIMIZED = 3;


        [STAThread()]
        static void Main()
        {
            Mutex studentMutex = MyMutex.TryEnter("IM.Client");
            if (studentMutex != null)
            {
                try
                {
                    // 登录IM
                    if (!LoginController.LoginIM())
                    {
                        if (Application.Current != null)
                            Application.Current.Shutdown();
                        return;
                    }

                    Application studentApp = new Application();
                    studentApp.MainWindow = new MainIMWindow();
                    studentApp.ShutdownMode = ShutdownMode.OnMainWindowClose;
                    studentApp.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(app_DispatcherUnhandledException);

                    // 启动主窗体
                    Application.Current.Run(studentApp.MainWindow);
                }
                finally
                {
                    MyMutex.TryRelease(studentMutex);
                }
            }
            else
            {
                Process[] processList = Process.GetProcessesByName("IM.Client");
                if (processList.Length > 0)
                {
                    foreach (Process p in processList)
                    {
                        if (p.Id != Process.GetCurrentProcess().Id)
                        {
                            ShowWindow(p.MainWindowHandle, SW_SHOWMAXIMIZED);
                            SetForegroundWindow(p.MainWindowHandle);
                        }
                    }
                }
            }
        }

        static void app_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.Message, "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
            e.Handled = true;
        }
    }
}
